package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.mapper.FlowMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.ThroadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Slf4j
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Autowired
    private IUserService userService;
    @Autowired
    private IBlogService blogService;
    @Autowired
    private ThroadLocal throadLocal;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private FlowMapper flowMapper;
    @Override
    public Result queryBlogById(Long id) {
         Blog blog = getById(id);
         if(blog == null){
              return Result.fail("笔记不存在");
         }
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    private void isBlogLiked(Blog blog) {
        Long userId = ThroadLocal.get().getId();
        String key = RedisConstants.BLOG_LIKED_KEY+blog.getId();
        Boolean isMember = stringRedisTemplate.opsForSet().isMember(key,userId.toString());
        if(isMember == true){
             blog.setIsLike(true);
        }
        else{
            blog.setIsLike(false);
        }
    }

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
       records.forEach(this::queryBlogUser);
        return Result.ok(records);
    }

    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());

    }

    @Override
    public Result likeBlog(Long id) {
         Long userId = ThroadLocal.get().getId();
         String key = RedisConstants.BLOG_LIKED_KEY+id;
         Boolean isMember = stringRedisTemplate.opsForSet().isMember(key,userId.toString());
         if(isMember == false){
              boolean isSuccess = update().setSql("liked = liked+1").eq("id",id).update();
              if(isSuccess){
                  stringRedisTemplate.opsForSet().add(key,userId.toString());
              }
         }
         else{
             boolean isSuccess = update().setSql("liked = liked-1").eq("id",id).update();
             stringRedisTemplate.opsForSet().remove(key,userId.toString());
         }
         return Result.ok();
    }

    @Override
    public Result saveBlog(Blog blog) {
        User user = ThroadLocal.get();
        blog.setUserId(user.getId());
        boolean isSuccess = save(blog);
        if(!isSuccess){
            return Result.fail("新增笔记失败");
        }
        List<Follow> follows = flowMapper.SelectByFollowUserId(user.getId());
        for(Follow follow: follows){
            Long userId = follow.getUserId();
            String key = "feed:"+userId;
            stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
        }

        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
       //获取当前用户
        Long currentId = ThroadLocal.get().getId();
        //查询收件箱
        String key  ="feed:"+currentId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 3);
        if(typedTuples == null ||typedTuples.isEmpty()){
            return Result.ok();
        }
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime = 0;
        int os = 1;
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
            ids.add(Long.valueOf(tuple.getValue()));
            //获取时间戳3
              long time  = tuple.getScore().longValue();
              if(time == minTime){
                  os++;
              }
              else{
                  minTime = time;
                  os = 1;
              }
        }
        String idStr = StrUtil.join(",",ids);
        List<Blog> blogs = query().in("id",ids).last("ORDER BY FIELD(id,"+ idStr +")").list();
        for (Blog blog : blogs) {
            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
            isBlogLiked(blog);
        }
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setOffset(os);
        scrollResult.setMinTime(minTime);
        return Result.ok(scrollResult);


    }
}
